// ***** BEGIN LICENSE BLOCK *****
// Version: MPL 1.1/GPL 2.0/LGPL 2.1
//
// The contents of this file are subject to the Mozilla Public License Version
// 1.1 (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
// http://www.mozilla.org/MPL/
//
// Software distributed under the License is distributed on an "AS IS" basis,
// WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
// for the specific language governing rights and limitations under the
// License.
//
// The Initial Developer of the Original Code is
//   Axel Nennker http://axel.nennker.de/ .
// Created by the Initial Developer are Copyright (C) 2011
// the Initial Developer. All Rights Reserved.

const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;

Cu.import("resource://gre/modules/Services.jsm");

var OpenIdPrefs = {
  _OpenIdStorage : null,
  
  getOpenIdStorage : function _getOpenIdStorage (){
    if (!OpenIdPrefs._OpenIdStorage) {
      OpenIdPrefs._OpenIdStorage = Components.classes['@openinfocard.com/openidstorage;1']
        .getService().wrappedJSObject;
    }
    return OpenIdPrefs._OpenIdStorage;
  },
  
  log : function log(aMessage) {
    Services.console.logStringMessage("openid prefs: " + aMessage);
  },

  onchange : function onchange(event) {
    try {
      var elt = document.getElementById("openidprovidertextbox");
      var value = elt.value;
//      OpenIdPrefs.log("onchange value=" + value);
      if (value && (value.trim() != "")) {
        try {
          OpenIdPrefs.getOpenIdStorage().setPreferredOpenID(value);
        } catch (ex) {
          OpenIdPrefs.log("onchange Exception: " + ex);
        }
      }
    } catch(e) {
      Components.utils.reportError(e);
    }
  },
  
  oncommand : function oncommand() {
//    OpenIdPrefs.log("oncommand! ");
    var list = document.getElementById("providerList");
    var item = list.selectedItem;
    if (item == null) {
      return;
    }
    var value;
    if (item.id == "openidprovidertextbox") {
      value = item.value;
    } else {
      value = item.getAttribute("label");
    }
    if (value) {
//      OpenIdPrefs.log("oncommand! value=" + value);
      try {
        OpenIdPrefs.getOpenIdStorage().setPreferredOpenID(value);
      } catch (ex) {
        OpenIdPrefs.log("OpenIdPrefs oncommand Exception: " + ex);
      }
    } else {
//      OpenIdPrefs.log("oncommand! label not defined. This should never happen!");
    }
  },
  
  onclear : function _onclear(event) {
//    OpenIdPrefs.log("onclear start");
    try {
      var openidstorage = OpenIdPrefs.getOpenIdStorage();
      openidstorage.deleteAllOpenIDs();
      openidstorage.unsetPreferredOpenID();
    } catch (e) {
      Components.utils.reportError(e);
    }
  },
  
  openAndReuseOneTabPerURL : function _openAndReuseOneTabPerURL(url) {
    var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                       .getService(Components.interfaces.nsIWindowMediator);
    var browserEnumerator = wm.getEnumerator("navigator:browser");

    // Check each browser instance for our URL
    var found = false;
    while (!found && browserEnumerator.hasMoreElements()) {
      var browserWin = browserEnumerator.getNext();
      var tabbrowser = browserWin.gBrowser;

      // Check each tab of this browser instance
      var numTabs = tabbrowser.browsers.length;
      for (var index = 0; index < numTabs; index++) {
        var currentBrowser = tabbrowser.getBrowserAtIndex(index);
        if (url == currentBrowser.currentURI.spec) {

          // The URL is already opened. Select this tab.
          tabbrowser.selectedTab = tabbrowser.tabContainer.childNodes[index];

          // Focus *this* browser-window
          browserWin.focus();

          found = true;
          break;
        }
      }
    }

    // Our URL isn't open. Open it now.
    if (!found) {
      var recentWindow = wm.getMostRecentWindow("navigator:browser");
      if (recentWindow) {
        // Use an existing browser window
        recentWindow.delayedOpenTab(url, null, null, null, null);
      }
      else {
        // No browser windows are open, so open a new one.
        window.open(url);
      }
    }
  },
  
  getanopenid : function _getanopenid(event) {
//    OpenIdPrefs.log("getanopenid start");
    try {
      OpenIdPrefs.openAndReuseOneTabPerURL("chrome://openidnascar/content/doIhaveAnOpenID.xul");
      window.close();
    } catch (e) {
      Components.utils.reportError(e);
    }
  },
  
  onloadSelect : function onloadSelect(event) {
//    OpenIdPrefs.log("onloadSelect start");
    try {
      var preferredOpenIdLogin = OpenIdPrefs.getOpenIdStorage().getPreferredOpenIdLogin();
      if (preferredOpenIdLogin) {
//        OpenIdPrefs.log("onload claimed_id =" + preferredOpenIdLogin.username);
//        OpenIdPrefs.log("onload password =" + preferredOpenIdLogin.password);
        OpenIdPrefs.populateProviderList(OpenIdPrefs.getOpenIdStorage(), preferredOpenIdLogin.username);
      } else {
        OpenIdPrefs.populateProviderList(OpenIdPrefs.getOpenIdStorage());
      }
    } catch(e) {
      Components.utils.reportError(e);
    }
  },
  
  onloadEdit : function onloadEdit(event) {
//    OpenIdPrefs.log("onloadEdit start");
    try {
      var preferredOpenIdLogin = OpenIdPrefs.getOpenIdStorage().getPreferredOpenIdLogin();
      if (preferredOpenIdLogin) {
//        OpenIdPrefs.log("onload claimed_id =" + preferredOpenIdLogin.username);
//        OpenIdPrefs.log("onload password =" + preferredOpenIdLogin.password);
        if (preferredOpenIdLogin.password == "{}") {
          var elt = document.getElementById("openidprovidertextbox");
          elt.value = preferredOpenIdLogin.username;
          elt.setAttribute("value", preferredOpenIdLogin.username);
        }
      }
    } catch(e) {
      Components.utils.reportError(e);
    }
  },
  
  trashIconHandler : function _trashIconHandler(anEvent) {
    try {
      var image = anEvent.target;
//      OpenIdPrefs.log("trashIconHandler id=" + image.id);
      var claimedid = image.getUserData("username");
      var host = image.getUserData("hostname");
      var preferredOpenidProvider = image.getUserData("preferredOpenidProvider");
//      OpenIdPrefs.log("trashIconHandler claimedid=" + claimedid);
//      OpenIdPrefs.log("trashIconHandler host=" + host);
      OpenIdPrefs.getOpenIdStorage().deleteOpenID(host, claimedid);
      window.close();
    } catch(e) {
      Components.utils.reportError(e);
    }
  },
	  
  openidIconHandler : function _openidIconHandler(anEvent) {
    try {
      var image = anEvent.target;
//      OpenIdPrefs.log("openidIconHandler id=" + image.id);
//      OpenIdPrefs.log("openidIconHandler src=" + image.src);
      var claimedid = image.getUserData("username");
      var host = image.getUserData("hostname");
      var preferredOpenidProvider = image.getUserData("preferredOpenidProvider");
//      OpenIdPrefs.log("openidIconHandler claimedid=" + claimedid);
//      OpenIdPrefs.log("openidIconHandler host=" + host);
      var args = {};
      args.host = host;
      args.preferredOpenidProvider = preferredOpenidProvider;
      args.claimedid = claimedid;
      args.out = null;
      var callback = function(imagesrc) {
    	  image.setAttribute("src", imagesrc);
      };
      window.openDialog("chrome://openidnascar/content/chooseImage.xul", 
    		  "openidnascar-choose-image-url", "chrome,dialog,modal,centerscreen,resizable=yes", args, callback);
    } catch(e) {
      Components.utils.reportError(e);
    }
  },
	  
  populateProviderList : function populateProviderList(preferredOpenidProvider) {
//    OpenIdPrefs.log("populateProviderList ");
    try {
      var logins = OpenIdPrefs.getOpenIdStorage().getAllOpenIDs();

      var providerListElt = document.getElementById("providerList");
      var children = providerListElt;
      for (var i = 0; i < children.length; i++) {
        var child = children[i];
        if ((child) && (child.id != "openidprovidertextbox")) {
          providerListElt.removeChild(child);
        }
      }
      var item; 
      var box;
      var trashImage;
      var image;
      
      for (var i=0; i<logins.length; i++) {
	    var itemBox = document.createElement("vbox");
        var spacer = document.createElement("spacer");
        spacer.setAttribute("flex", "1");
        itemBox.appendChild(spacer);
        
        item = document.createElement("radio");
        var login = logins[i];
//        OpenIdPrefs.log("populateProviderList: login.username=" + login.username);
        item.setAttribute("label", unescape(login.username));
        item.setAttribute("id", login.username);
        if (preferredOpenidProvider == login.username) {
          item.setAttribute("selected", true);
        }
        itemBox.appendChild(item);
        spacer = document.createElement("spacer");
        spacer.setAttribute("flex", "1");
        itemBox.appendChild(spacer);
        
        box = document.createElement("hbox");
        box.setAttribute("id", "box_"+login.username);

        var trashBox = document.createElement("vbox");
        spacer = document.createElement("spacer");
        spacer.setAttribute("flex", "1");
        trashBox.appendChild(spacer);
        trashImage = document.createElement("image");
        trashImage.setAttribute("width", "16px");
        trashImage.setAttribute("height", "16px");
        trashImage.setAttribute("src", "chrome://openidnascar/content/trash-icon.gif");
        trashImage.setAttribute("id", "trash_image_"+login.username);
//        trashImage.setAttribute("style", "width:16px; height:16px; padding:4px");
        trashImage.addEventListener("click", OpenIdPrefs.trashIconHandler, false);
        trashImage.setUserData("username", login.username, null);
        trashImage.setUserData("hostname", login.hostname, null);
        trashImage.setUserData("preferredOpenidProvider", preferredOpenidProvider, null);
        trashBox.appendChild(trashImage);
        spacer = document.createElement("spacer");
        spacer.setAttribute("flex", "1");
        trashBox.appendChild(spacer);
        
        var imageBox = document.createElement("vbox");
        spacer = document.createElement("spacer");
        spacer.setAttribute("flex", "1");
        imageBox.appendChild(spacer);
        var realm = login.hostname;
        var claimedid = login.username;
        var openidstorage = OpenIdPrefs.getOpenIdStorage();
        var dataUrl = openidstorage.getImage(claimedid, realm);
        image = document.createElement("image");
        image.setAttribute("width", "16px");
        image.setAttribute("height", "16px");
        if (dataUrl) {
//        	OpenIdPrefs.log("populateProviderList: dataUrl=" + dataUrl);
//        	image.setAttribute("src", "chrome://openidnascar/content/openid-16x16.gif");
        	image.setAttribute("src", dataUrl);
        } else {
        	image.setAttribute("src", "chrome://openidnascar/content/openid-16x16.gif");
        }
        image.setAttribute("id", "image_"+login.username);
//        image.setAttribute("style", "width:16px; height:16px; padding:4px");
        image.addEventListener("click", OpenIdPrefs.openidIconHandler, false);
        image.setUserData("username", login.username, null);
        image.setUserData("hostname", login.hostname, null);
        image.setUserData("preferredOpenidProvider", preferredOpenidProvider, null);
        imageBox.appendChild(image);
        spacer = document.createElement("spacer");
        spacer.setAttribute("flex", "1");
        imageBox.appendChild(spacer);
        
        box.appendChild(trashBox);
        box.appendChild(imageBox);
        box.appendChild(itemBox);
        providerListElt.appendChild(box);
      }
    } catch (ex) {
      Components.utils.reportError(e);
    }
  }

};
